﻿using System;
using System.Net;
using System.Windows;



using System.Windows.Input;
using System.IO;
using System.Globalization;
using System.Text;
using System.Collections.Generic;

namespace G.Net.Oauth
{
    /// <summary>
    /// 主要用来上传文件和图片用的
    /// </summary>
    public class OauthFilePost : HttpPost
    {
        string boundary;
        public OauthFilePost(string uri)
            : base(uri)
        {
            boundary = Guid.NewGuid().ToString();
            base.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
        }
        private ParamCollection postParams = new ParamCollection();
        public ParamCollection Params
        {
            get
            {
                return postParams;
            }
        }

        protected override void AppendHeaders(System.Net.Http.Headers.HttpRequestHeaders headers)
        {
            base.AppendHeaders(headers);
            var parameters = OauthSignHelper.GetOAuthBasicParams();

            parameters.Add(Constants.OAuthToken, OauthConfiger.AccessToken.Token);

            var oAuthHeader = OauthSignHelper.ConstructOAuthHeader(parameters, HttpMethod.Post, Uri, OauthConfiger.AccessToken.Secret);

            headers.Add("Authorization", oAuthHeader);

        }
        public byte[] FileBuffer { get; set; }
        protected override System.Net.Http.HttpContent WriteBody()
        {
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.Append("--");
            sBuilder.Append(boundary);
            sBuilder.Append("\r\n");
            sBuilder.Append("Content-Disposition: form-data; name=\"" + "source" + "\"\r\n\r\n");
            sBuilder.Append(OauthConfiger.AppKey);
            sBuilder.Append("\r\n");

            foreach (var item in this.Params)
            {
                sBuilder.Append("--");
                sBuilder.Append(boundary);
                sBuilder.Append("\r\n");
                sBuilder.Append("Content-Disposition: form-data; name=\"" + item.Name + "\"\r\n\r\n");
                sBuilder.Append(System.Net.WebUtility.UrlEncode(item.Value));
                sBuilder.Append("\r\n");
            }
            System.IO.Stream reqStream = new System.IO.MemoryStream();

            reqStream.Write(sBuilder.ToString().GetBytes());
            StringBuilder split = new StringBuilder();
            split.Append("--");
            split.Append(boundary);
            split.Append("\r\n");
            split.Append("Content-Disposition: form-data;name=\"pic\";filename=\"temp.jpg\"\r\n");
            split.Append("Content-Type: image/jpg\r\n\r\n");
        
            reqStream.Write(split.ToString().GetBytes());
            reqStream.Write(FileBuffer);
            reqStream.Write(("\r\n--" + boundary + "--\r\n").GetBytes());

            return new System.Net.Http.StreamContent(reqStream);
        }

    }
}
